package cn.relx.org.controller;

import cn.relx.basic.annotation.PreAuthorize;
import cn.relx.basic.util.AjaxResult;
import cn.relx.basic.util.LoginContext;
import cn.relx.basic.util.PageList;
import cn.relx.org.domain.Department;
import cn.relx.org.query.DepartmentQuery;
import cn.relx.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;

    /**
     * 添加/修改
     */
    @PutMapping
    @PreAuthorize(name = "添加和修改部门" ,sn = "department:addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        if (null == department.getId()){
            // 添加
            departmentService.add(department);
        }else {
            // 修改
            departmentService.update(department);
        }
        return AjaxResult.me().success();
    }

    /**
     * 删除 delete localhost:8080/dept/1
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除部门" ,sn = "department:delete")
    public AjaxResult delete(@PathVariable("id") Long id){
        departmentService.delete(id);
        return AjaxResult.me().success();
    }

    /**
     * 查询所有
     */
    @GetMapping
    @PreAuthorize(name = "查询部门" ,sn = "department:findAll")
    public List<Department> findAll(){
        return departmentService.findAll();
    }

    /**
     * 根据id查询一个
     */
    @GetMapping("/{id}")
    @PreAuthorize(name = "查询单个部门" ,sn = "department:findById")
    public Department findById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    /**
     *
     * 分页查询
     */
    @PostMapping
    @PreAuthorize(name = "查询分页部门" ,sn = "department:queryByPage")
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query, HttpServletRequest request){
        Object userInfo = LoginContext.getLoginUser(request);
        return departmentService.queryByPage(query);
    }

    @PatchMapping
    @PreAuthorize(name = "批量删除部门" ,sn = "department:batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids){
        departmentService.batchDel(ids);
        return AjaxResult.me().success();
    }

    @PostMapping("/tree")
    @PreAuthorize(name = "查询部门树" ,sn = "department:deptTree")
    public List<Department> deptTree() {
        return departmentService.deptTree();
    }
}
